package com.ophiux.cs.application.consult.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ophiux.cs.application.consult.dto.CSConInitRequest;
import com.ophiux.cs.application.consult.dto.CSLoginRequest;
import com.ophiux.cs.application.consult.dto.CSRegisterResponse;
import com.ophiux.cs.application.consult.service.ICSUserRegisterAppService;
import com.ophiux.cs.application.core.Result;
import com.ophiux.cs.domain.consult.model.entity.CSUser;
import com.ophiux.cs.domain.consult.model.factory.CSUserBuilder;
import com.ophiux.cs.domain.consult.repositories.IUserInfoRepository;
import com.ophiux.utils.exception.OphiuxParamException;
import com.ophiux.utils.exception.OphiuxRepositoryException;

/**
 * 咨询用户注册
 * @author chenh
 *
 */
@Service("cSUserRegisterAppService")
public class CSUserRegisterAppService implements ICSUserRegisterAppService{

	@Autowired
	IUserInfoRepository cSUserInfoRepository;	//用户信息仓储
	
	
	@Override
	public Result<CSRegisterResponse> CSRegister(CSConInitRequest request) {
		
		Result<CSRegisterResponse> result = null;
		
		/**参数合法性验证**/
		if(!request.isParamValid()) {
			return Result.fail("", "参数不合法");
		}
		
		//根据账号获取用户信息
		String targetAcc = request.getTARGET_ACC();
		CSUser csUser = null;
		try {
			csUser = cSUserInfoRepository.getCSUserByTargetACC(targetAcc);
		} catch (OphiuxRepositoryException e) {
			e.printStackTrace();
			return Result.fail("", e.getExceptionMessage());
		}
		
		//判断用户是否存在，不存在，就注册;存在：返回用户已存在，不可重复注册
		if(csUser != null && csUser.isValid()) {
			result = Result.fail("", "该用户已注册，不可重复注册");
		}
		//新增咨询用户
		try {
			csUser = CSUserBuilder.getInstance().build(request.getTARGET_ACC(), 
					request.getTARGET_NAME(),request.getSEX(),"", request.getPHOTO_URL());
		} catch (OphiuxParamException e) {
			e.printStackTrace();
			result = Result.fail("", e.getExceptionMessage());
		}
		
		//保存用户
		try {
			cSUserInfoRepository.save(csUser);
		} catch (OphiuxRepositoryException e) {
			e.printStackTrace();
			return Result.fail("", e.getExceptionMessage());
		}
		//注册成功，返回用户标识
		String targetID = csUser.getTARGET_ID();
		CSRegisterResponse regResponse = new CSRegisterResponse(targetID);
		result = Result.success(regResponse);
		
		return result;
	}


}
